/**
 * Created by jiachenpan on 16/11/18.
 */
import store from '@/store';
import moment from 'moment';
import { isEmpty } from 'rxjs/operators';
import dictionaryData from "./dictionary";
import request from '@/utils/request'
import { userPage, } from '@/api/after-sale/personnel/index'
import { page } from '@/api/after-sale/personnel/team'
import { dictStoreSysConfigDict, dictPage } from '@/api/after-sale/dictionary'
import { excelExport } from '@/api/after-sale/excelExport'
import {
  getToken
} from './auth'
export function parseTime (time, cFormat = 'YYYY-MM-DD') {
  if (arguments.length === 0) {
    return null
  }
  return moment(time).format(cFormat)
}

export function parseTimeToYMDHMS (time, cFormat = 'YYYY-MM-DD HH:mm:ss') {
  if (arguments.length === 1) {
    return moment(time).format(cFormat)
  }
  if (arguments.length === 2) {
    return moment(time).format(cFormat)
  }
  return null;
}
moment(new Date(), "YYYY-MM-DD HH:mm:ss")

export function formatTime (time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

// 格式化时间
export function getQueryObject (url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 *get getByteLen
 * @param {Sting} val input value
 * @returns {number} output value
 */
export function getByteLen (val) {
  let len = 0
  for (let i = 0; i < val.length; i++) {
    if (val[i].match(/[^\x00-\xff]/ig) != null) {
      len += 1
    } else { len += 0.5 }
  }
  return Math.floor(len)
}

export function cleanArray (actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

export function param (json) {
  if (!json) return ''
  return cleanArray(Object.keys(json).map(key => {
    if (json[key] === undefined) return ''
    return encodeURIComponent(key) + '=' +
      encodeURIComponent(json[key])
  })).join('&')
}

export function param2Obj (url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
}

export function html2Text (val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

export function objectMerge (target, source) {
  /* Merges two  objects,
     giving the last one precedence */

  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach((property) => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

export function scrollTo (element, to, duration) {
  if (duration <= 0) return
  const difference = to - element.scrollTop
  const perTick = difference / duration * 10
  setTimeout(() => {
    element.scrollTop = element.scrollTop + perTick
    if (element.scrollTop === to) return
    scrollTo(element, to, duration - 10)
  }, 10)
}

export function toggleClass (element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

export const pickerOptions = [
  {
    text: '今天',
    onClick (picker) {
      const end = new Date()
      const start = new Date(new Date().toDateString())
      end.setTime(start.getTime())
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一周',
    onClick (picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(end.getTime() - 3600 * 1000 * 24 * 7)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近一个月',
    onClick (picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      picker.$emit('pick', [start, end])
    }
  }, {
    text: '最近三个月',
    onClick (picker) {
      const end = new Date(new Date().toDateString())
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      picker.$emit('pick', [start, end])
    }
  }]

export function getTime (type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}



export function deepClone (source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach((keys) => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = source[keys].constructor === Array ? [] : {}
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

export async function getAreaName (provinceId, cityId, countyId) {
  let counties
  if (provinceId) {
    const province = store.getters.area.find(({ id }) => id === provinceId)
    const cities =
      province.children.length === 0 ? await store.dispatch('setCity', province.value) : province.children

    if (cityId) {
      const city = cities.find(({ id }) => id === cityId)
      counties =
        city.children.length === 0
          ? await store.dispatch('setCounty', { provinceCode: province.value, cityCode: city.value })
          : city.children

      if (countyId) {
        const county = counties.find(({ id }) => id === countyId)
        return { provinceName: province.label, cityName: city.label, countyName: county.label }
      } else {
        return { provinceName: province.label, cityName: city.label }
      }
    } else {
      return { provinceName: province.label }
    }
  } else {
    return {}
  }
}

export function getListDegreeData (datas) {
  var dataArray = []
  datas.forEach(function (data) {
    var degree = data.degree
    if (degree === 2) {
      var objTemp = {
        value: data.id,
        label: data.value,
        parentId: data.parentId,
        degree: data.degree
      }
      dataArray.push(objTemp)
    }
  })
  return data2treeDegree(datas, dataArray)
}
export function data2treeDegree (datas, dataArray) {
  for (let j = 0; j < dataArray.length; j++) {
    var dataArrayIndex = dataArray[j]
    var childrenArray = []
    var Id = dataArrayIndex.value
    for (let i = 0; i < datas.length; i++) {
      var data = datas[i]
      var parentId = data.parentId
      if (parentId === Id) {
        var objTemp = {
          value: data.id,
          label: data.value,
          parentId: parentId
        }
        childrenArray.push(objTemp)
      }
    }
    if (childrenArray.length > 0) {
      dataArrayIndex.children = childrenArray
      data2treeDegree(datas, childrenArray)
    } else {
      if (dataArrayIndex.degree === 2) {
        dataArrayIndex.disabled = true
      }
    }
  }
  return dataArray
}
export function getListData (datas) {
  var dataArray = []
  datas.forEach(function (data) {
    var parentId = data.parentId
    if (parentId === '') {
      var objTemp = {
        value: data.id,
        label: data.value,
        parentId: parentId
      }
      dataArray.push(objTemp)
    }
  })
  return data2treeDG(datas, dataArray)
}
export function data2treeDG (datas, dataArray) {
  for (let j = 0; j < dataArray.length; j++) {
    var dataArrayIndex = dataArray[j]
    var childrenArray = []
    var Id = dataArrayIndex.value
    for (let i = 0; i < datas.length; i++) {
      var data = datas[i]
      var parentId = data.parentId
      if (parentId === Id) {
        var objTemp = {
          value: data.id,
          label: data.value,
          parentId: parentId
        }
        childrenArray.push(objTemp)
      }
    }
    if (childrenArray.length > 0) {
      dataArrayIndex.children = childrenArray
      data2treeDG(datas, childrenArray)
    }
  }
  return dataArray
}

export function dataParent (datas, childrenId) {
  var dataList = []
  dataList.push(childrenId)
  for (let j = 0; j < datas.length; j++) {
    var data = datas[j]
    if (data.id === childrenId) {
      if (data.parentId != '') {
        dataList.unshift(data.parentId)
        for (let k = 0; k < datas.length; k++) {
          var data1 = datas[k]
          if (data1.id === data.parentId) {
            if (data1.parentId != '') {
              dataList.unshift(data1.parentId)
            }
          }
        }
      }
    }
  }
  return dataList
}

/**
 * 对象中空串转为null
 * '' => null
 * @param {*} data 要处理的数据
 */
export function emptyStrToNull (data) {
  for (let x in data) {
    if (data[x] === '') {
      data[x] = null;
    } else {
      if (Array.isArray(data[x])) {
        data[x] = data[x].map(z => {
          return emptyStrToNull(z);
        });
      }
      if (typeof (data[x]) === 'object') {
        data[x] = emptyStrToNull(data[x])
      }
    }
  }
  return data;
}
/**
 * 获取服务器实时字典
 */
export async function getServerDict (dictName) {
  let { data } = await dictStoreSysConfigDict(dictName)
  return data;
  // console.log('请求字典获取值',data)
  // let b = [];
  // if (!dictName) {
  //   return b
  // }
  // let form = {
  //   storeId: getStoreId(), //门店
  //   dictValue: '', //字典类型
  //   dictKey: dictName, //字典值
  // };
  // let { success, data } = await dictPage(form, 1000, 1)
  // if (success) {
  //   data.content && data.content.map((item, index) => {
  //     if (item.storeId && item.storeId == 0 || item.storeId == getStoreId())
  //       b.push({ index: index, text: item.dictValue, value: item.id, storeId: item.storeId || '' },)
  //   })
  // }
  // if (b.length > 1) {
  //   let b2 = b.map(item => {
  //     if (item == getStoreId()) {
  //       return item
  //     }
  //   })
  //   if (b2.length > 0)
  //     b = b2;
  // }
  // return { [dictName]: b };
}
/**
   * 获取字典
   * 必输参数 arguments[0] Arry 查询字典 例: ["客户类型","客户来源"]
   * 可选参数 arguments[1] String||Inter 门店id  例: 1
   * 可选参数 arguments[2] String||Inter 是否补齐门店  例: true，限定，flase不限定
   */
export function getDict () {
  let args = arguments;
  let _storeId = store.state.user.entryStore; //默认获取入职门店

  let _limitedStoreid = args[2] ? args[2] : false;//是否不查询工共字典
  if (args.length === 1) {
    return dictFilter(args[0], _storeId)
  } else {
    return dictFilter(args[0], args[1] ? args[1] : _storeId, _limitedStoreid)
  }
}
/**
* 过滤系统字典
* @param {*} dictArry
* @param {*} _storeId
*/
function dictFilter (dictArry, _storeId, _limitedStoreid) {
  let returnDict = {}, c = [];
  if (Array.isArray(dictArry) && dictArry.length > 0) {
    dictArry.forEach((item, index) => {
      if (dictionaryData[item]) {
        returnDict[item] = dictionaryData[item];
      } else {
        c.push(item)
      }
    })
    if (c.length > 0) {
      c.forEach(item => {
        let value = dictFilterDictAryy(item, _storeId, _limitedStoreid)
        if (value && value.length > 0) {
          returnDict[item] = value;
        }
      })
    }

  }
  return returnDict;
}
//过滤非系统字典
function dictFilterDictAryy (dictKey, _storeId, _limitedStoreid) {
  // TODO 假如存在多个平台，则平台的公共字典是当前平台门店id  而非现在的1为公共字典
  let b = [];
  let _dictArry = store.state.dictionary.dictionary;
  let returnData = _dictArry.filter(item => {
    //是否补齐门店
    if (item.dictKey === dictKey && (_limitedStoreid ? item.storeId == _storeId : (item.storeId == 1 || item.storeId == _storeId))) {
      return item
    }
  })
  if (returnData.length > 0) {
    returnData.forEach((item, index) => {
      b.push({ index: index, text: item.dictValue, value: item.id },)
    })
  }
  return b
}
/**
 * 获取图片地址
 * @param {*} id
 */
export function getImageUrl (id) {
  //TODO 要判断生产环境 待验证
  return id ? `${process.env.BASE_API}/base/attachment/files/id/${id}` : ''
}

/**
 * 文件上传
 * @param {*} file file对象
 */
export async function fileUpload (file, fileType) {
  let formData = new FormData();
  formData.append('file', file);
  formData.append('prefixMenu', fileType ? fileType : 'image')
  let res = await request.post('/base/attachment/upload', formData);
  return res;
}

/**
 * 获取当前选中门店或入职门店
 */
export function getStoreId () {
  return store.getters.storesCalue ? store.getters.storesCalue : store.state.user.entryStore;
}

/**
 * 行驶证识别
 */
export async function drivingLicenseRecognition (file, side = 0) {
  let formData = new FormData();
  formData.append('file', file);
  formData.append('side', side)
  let res = await request.post('/base/vehicle/license', formData);
  return res;
}

/**
 * 对象赋值
 * @param {*} target 目标对象
 * @param {*} source 数据源
 */
export function objectAssignment (target, source) {
  if (source) {
    Object.keys(target).forEach(item => {
      if (typeof target[item] == 'object') {
        if (Array.isArray(target[item])) {
          target[item] = source[item]
        } else {
          objectAssignment(target[item], source[item])
        }
      } else if (`${item}` in source) {
        target[item] = source[item]
      }
    })
  }
  return target;
}

/**
 * 获取当前门店下的员工和班组
 */
export async function getUserOrTem () {
  let arry = sessionStorage.getItem(`${getStoreId()}UserList`) || [], t = false;
  if (arry.length == 0) {
    t = true;
    let { data: { content: list1 } } = await userPage({ storeId: getStoreId() }, 200, 1);//员工数据,当前门店下
    let { data: { content: list2 } } = await page({ storeId: getStoreId() }, 200, 1);//班组数据,当前门店下
    //workUserType 作业人员类型  0 员工 1班组
    list1.forEach(item => { arry.push({ value: `${item.userName}_员工`, id: item.id, workUserType: 0 }) });
    list2.forEach(item => { arry.push({ value: `${item.teamName}_班组`, id: item.id, workUserType: 1 }) });
    sessionStorage.setItem(`${getStoreId()}UserList`, JSON.stringify(arry));
  }
  return t ? arry : JSON.parse(arry);
}

/**
 *  向上获取对应refsName组件
 * @param {*} refsName
 * @param {*} vm  当前vm.$parent对象
 */
export function getRefs (refsName, vm) {
  try {
    if (`${refsName}` in vm.$refs) {
      console.log('找到对应', refsName, vm.$refs, vm.$refs[refsName])
      return vm.$refs[refsName]
    } else {
      if ('$parent' in vm) {
        return getRefs(refsName, vm.$parent)
      }
    }
  } catch (error) {
    throw new Error(error)
  }
}

/**
 * 获取当前员工信息
 */
export function getUser () {
  return store.state.user;
}

/**
 * 函数节流
 * @param {*} func
 * @param {*} delay
 */
export function throttle (func, delay) {
  var timer = null;
  var startTime = Date.now();
  return function () {
    var curTime = Date.now();
    var remaining = delay - (curTime - startTime);
    var context = this;
    var args = arguments;
    clearTimeout(timer);
    if (remaining <= 0) {
      func.apply(context, args);
      startTime = Date.now();
    } else {
      timer = setTimeout(func, remaining);
    }
  }
}
/**
 * 函数防抖
 * @param {*} func
 * @param {*} wait
 * @param {*} immediate
 */
export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * 对象属性更改
 * @param {*} source 对象或数组
 * @param {*} targe  目标key
 * @param {*} fideName 目标key转成对应字段名
 */
export function conversionObjectField (source, targe, fideName) {
  if (!Array.isArray(source)) {
    if (Object.keys(source).length > 0) {
      for (let item in source) {
        if (targe && fideName && item == targe) {
          source[fideName] = source[targe];
          //TODO 可以新增后删除原对象
        }
      }
    }
  } else {
    return source.map(item => {
      return conversionObjectField(item, targe, fideName)
    })
  }

  return source;
}
function download (data, fileName) {
  if (!data) {
    return
  }
  let url = window.URL.createObjectURL(new Blob([data]))
  let link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  link.setAttribute('download', `${fileName || 'excels'}.xls`)

  document.body.appendChild(link)
  link.click()
}

/**
 * Excel 导出
 * @param {*} dataType 模块
 * @param {*} fileName  文件名
 * @param {*} param  查询参数
 * @param {*} pageSize 分页大小
 * @param {*} pageNo 分页页码
 */
export function exportExcel (dataType, fileName, param, pageSize, pageNo) {
  excelExport(dataType, param, pageSize, pageNo).then(res => {
    download(res, fileName)
  })
}
/**
 * 生成唯一id
 */
export function uuid () {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
}
/**
 * 权限函数  适用于input输入框或者全局指令无法满足时，用v-if做权限控制
 * @param {*} value 
 */
export function permission (value) {
  const btnPermission = store.getters.buttons
  const { account } = store.getters.userInfo
  if (account === 'admin' || value == 'admin') {
    return true;
  }
  else if (value && btnPermission.includes(value)) {
    return true
  }
  return false
}

export function exportFile (url, filename) {
  // let param = Qs.stringify(params)
  var xmlResquest = new XMLHttpRequest();
  xmlResquest.open("GET", url, true);
  xmlResquest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlResquest.setRequestHeader("token", getToken());
  xmlResquest.responseType = "blob";
  xmlResquest.onload = function (oEvent) {
    var content = xmlResquest.response;
    var elink = document.createElement('a');
    elink.download = filename;
    elink.style.display = 'none';
    var blob = new Blob([content]);
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    elink.click();
    document.body.removeChild(elink);
  };
  xmlResquest.send();
}

//间隔时间-天
export function getDateDiff (startDate, endDate) {
  var startTime = new Date(Date.parse(startDate.replace(/-/g, "/"))).getTime();
  var endTime = new Date(Date.parse(endDate.replace(/-/g, "/"))).getTime();
  var dates = Math.abs((startTime - endTime)) / (1000 * 60 * 60 * 24);
  return dates;
}